<template>
  <div class="tinymce-wrapper">
    <Editor :id="id" v-model="tinymceHtml" :init="init"></Editor>
  </div>
</template>

<script>
import tinymce from 'tinymce/tinymce';
import 'tinymce/themes/silver';
import 'tinymce/icons/default/icons.js';
import Editor from '@tinymce/tinymce-vue';

import 'tinymce/plugins/link';
import 'tinymce/plugins/code';
import 'tinymce/plugins/table';
import 'tinymce/plugins/hr';
import 'tinymce/plugins/lists';
import 'tinymce/plugins/advlist';
import 'tinymce/plugins/fullscreen';
import 'tinymce/plugins/contextmenu';
import 'tinymce/plugins/wordcount';
import 'tinymce/plugins/textcolor';
import 'tinymce/plugins/image';
import 'tinymce/plugins/media';
import 'tinymce/plugins/wordcount';

export default {
  name: 'Tinymce',
  components: {
    Editor,
  },
  props:{
    height:Number,
    placeholder:String,
    id:{
      type:String,
      required:true,
      default: function() {
        return `vue-tinymce-${new Date()}${((Math.random() * 1000).toFixed(0))}`
      }
    },
    contextUrl:{
      type:String,
      default:undefined
    },
    context:{
      type:String,
      default:undefined
    },
    t_id:{
      type:Number,
    }
  },
  created(){
    if(this.contextUrl){
      this.getContext(this.contextUrl);
    }
    this.to_init();
  },
  data() {
    return {
      tinymceHtml: this.context || '',
      tinymceId:this.id,
      init: {
        selector:'#' + this.id,
        // skin: 'oxide-dark',
        content_css: 'dark',
        placeholder:this.placeholder,
        language_url: '/tinymce/langs/zh_CN.js', //语言包路径
        language: 'zh_CN', //语言设置为中文
        height: this.height,
        skin_url: '/tinymce/skins/ui/oxide', //皮肤包
        plugins: 'link lists advlist fullscreen image wordcount powerpaste hr',
        powerpaste_word_import: 'merge',
        powerpaste_allow_local_images: true,
        powerpaste_html_import: 'merge',
        external_plugins: {
          powerpaste: '/tinymce/plugins/powerpaste/plugin.min.js',
        },
        menubar:true,
        toolbar:
          'undo redo | fontselect fontsizeselect | formatselect hr| bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lists image media table | removeformat',
        branding: true,
        image_caption: true,
        image_advtab: true,
        image_uploadtab: true,
        paste_data_images: true,
        images_reuse_filename:true,
        image_list: [
        ],
        images_upload_handler:this.handleImgUpload
      },
    };
  },
  methods: {
    async handleImgUpload(blobInfo,success,failure,progress) {
      let formdata = new FormData();
      formdata.append('img_file', blobInfo.blob());
      var res = await this.$post({
        url:'/fs/',
        data:formdata,
        options:{
          onUploadProgress: progressEvent => {
            let complete = (progressEvent.loaded / progressEvent.total * 100 | 0) + '%'
            self.uploadMessage = '上传 ' + complete
          },
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }
      })
      if(res.status === 200) {
        success('/fs/'+res.data);
      }
      
    },
    onPaste(event) {
      // return;
      // 实现图片粘贴上传
      const items = (event.clipboardData || window.clipboardData).items;

      // 搜索剪切板items 只取第一张
      if (items[0].type.indexOf('image') !== -1) {
        console.log('粘贴的是图片类型');
        const file = items[0].getAsFile();
        const formData = new FormData();
        formData.append('file', file);
        // 上传图片
        UpLoadImg(formData).then((res) => {
          console.log(res);
          if (res.code === 200) {
            // 放到内容当中
            window.tinymce
              .get(this.tinymceId)
              .insertContent(`<img class="wscnph" src="${res.data.image}" >`);
          } else {
            this.$message.error('图片上传失败,联系开发人员');
          }
        });
      } else {
        console.log('粘贴的不是图片，不能上传');
      }
    },
    to_destroy(){
      console.log('tinymce destory');
      tinymce.editors[this.id].destroy();
    },
    to_init(){
      console.log('init',this.init.selector);
      tinymce.init(this.init);
      console.log(tinymce.editors);
      // tinymce.editors[this.id].setContent('');
    },
    capsEvent(){
      console.log('---');
      this.$message({
        type:'info',
        message:'大写'
      })
    },
    async upload(url){
      var res = await this.$post({
        url,
        data:{
          t_id:this.t_id,
          context:this.tinymceHtml
        }
      })
      console.log(res);
    },
    async getContext(url){
      console.log('tinymce get context from '+ url);
      var res = await this.$get({
        url,
        data:{
          t_id:this.t_id
        }
      })
      console.log(res);
      this.tinymceHtml = res.data;
    }
  },
  beforeUnmount(){
    console.log('beforeUnmount');
  },
  watch:{
    context(newValue,oldValue){
      this.tinymceHtml = newValue;
    },
  }
};
</script>

<style lang="less" scoped>
.tinymce-wrapper{
  width: 100%;
}
</style>